﻿Imports Microsoft.TeamFoundation
Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Client
Imports Microsoft.TeamFoundation.Framework.Client
Imports System.Net
Imports Microsoft.TeamFoundation.VersionControl.Client

Public Class TFSWorkItemSelector

    Private store As WorkItemStore

    Public Shared Function SelectWorkItem(store As WorkItemStore, ByRef wiID As Integer) As Boolean
        Dim frm As New TFSWorkItemSelector(store)
        Dim result As DialogResult = frm.ShowDialog
        If result = Windows.Forms.DialogResult.Cancel Then Return False
        Dim wi As WorkItem = frm.dgWorkItems.SelectedRows(0).DataBoundItem
        wiID = wi.Id
        Return True
    End Function

    Public Sub New(store As WorkItemStore)
        Me.InitializeComponent()
        Me.store = store
    End Sub

    Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
        If cmbTeamProjects.Text.Trim() = "" Then
            MessageBox.Show("You must select a Team Project")
            Exit Sub
        End If

        Dim title As String = ""
        If txtTitle.Text.Trim() <> "" Then title = " AND [System.Title] CONTAINS '" + txtTitle.Text + "'"

        Dim state As String = ""
        If cmbState.Text.Trim() <> "" Then
            state = " AND [System.State] = '" + cmbState.Text + "'"
        End If

        Dim wiType As String = ""
        If cmbWorkItemType.Text.Trim() <> "" Then
            wiType = " AND [System.WorkItemType] = '" + cmbWorkItemType.Text + "'"
        End If

        Dim witCollection As WorkItemCollection = store.Query("Select ID, Title FROM Issue WHERE [System.TeamProject] = '" + cmbTeamProjects.Text + "'" _
                                                              + title + state + wiType)

        dgWorkItems.DataSource = witCollection

    End Sub

    Private Sub TFSWorkItemSelector_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        LoadLookups()
    End Sub

    Private Sub LoadLookups()
        For Each prj As Project In store.Projects
            cmbTeamProjects.Items.Add(prj.Name)
        Next
    End Sub

    Private Sub btnOK_Click(sender As System.Object, e As System.EventArgs) Handles btnOK.Click
        Me.DialogResult = DialogResult.OK
    End Sub

End Class